package com.spring.sunflower.util;

import android.content.Context;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Kevin on 2021/8/26<br/>
 * <p>
 * Describe:<br/>
 */
public class LocationUtils {
    private static LocationUtils mInstance;
    private static Context mContext;
    private LocationClient locationClient;

    public static LocationUtils getInstance(Context context) {
        mContext = context;
        if (mInstance == null) {
            synchronized (LocationUtils.class) {
                if (mInstance == null) {
                    mInstance = new LocationUtils();
                }
            }
        }
        return mInstance;
    }

    public void registerLocation() {
        locationClient = new LocationClient(mContext);
        locationClient.registerLocationListener(new BDAbstractLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation bdLocation) {
                Map<String, String> map = new HashMap<>();
                String city = bdLocation.getCity();
                String province = bdLocation.getProvince();
                map.put("latitude", String.valueOf(bdLocation.getLatitude()));
                map.put("longitude", String.valueOf(bdLocation.getLongitude()));
                map.put("city", city);
                map.put("province", province);
                LogUtils.INSTANCE.logD("LocationUtils", "纬度=" + bdLocation.getLatitude() + "，经度=" + bdLocation.getLongitude() + "" +
                        "city=" + city + ",province=" + province);
                if (listener != null) {
                    listener.onLocationGet(map);
                }

            }
        });
        LocationClientOption locationClientOption = new LocationClientOption();
        locationClientOption.setScanSpan(1000);
        locationClientOption.setIgnoreKillProcess(true);
        locationClientOption.setIsNeedAddress(true);
        locationClient.setLocOption(locationClientOption);
        locationClient.start();
    }

    public void stop() {
        if (locationClient != null) {
            locationClient.stop();
        }
    }

    public void setOnLocationGetListener(OnLocationGetListener l) {
        listener = l;
    }

    private OnLocationGetListener listener;

    public interface OnLocationGetListener {
        void onLocationGet(Map<String, String> map);
    }
}
